
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.PrintStream;

import javax.swing.JLabel;
import javax.swing.RepaintManager;

public class PrintUtilities implements Printable {
	private Component componentToBePrinted;

	public static void printComponent(Component c) {
		new PrintUtilities(c).print();
	}

	public PrintUtilities(Component componentToBePrinted) {
		this.componentToBePrinted = componentToBePrinted;
	}

	public void print() {
		PrinterJob printJob = PrinterJob.getPrinterJob();
		printJob.setPrintable(this);
		if (printJob.printDialog())
			try {
				printJob.print();
			} catch (PrinterException pe) {
				System.out.println("Error printing: " + pe);
			}
	}

	public int print(Graphics g, PageFormat pf, int pageIndex) {
		pf.setOrientation(0);

		int response = 1;
		Graphics2D g2 = (Graphics2D) g;

		disableDoubleBuffering(this.componentToBePrinted);

		Dimension d = this.componentToBePrinted.getSize();
		double panelWidth = d.width;
		double panelHeight = d.height;
		double pageHeight = pf.getImageableHeight();
		double pageWidth = pf.getImageableWidth();

		double scaleX = pageWidth / panelWidth;
		double scaleY = pageHeight / panelHeight;

		int totalNumPages = (int) Math.ceil(scaleY * panelHeight / pageHeight);

		if (pageIndex >= totalNumPages) {
			response = 1;
		} else {
			g2.translate(pf.getImageableX(), pf.getImageableY());

			g2.translate(0.0D, -pageIndex * pageHeight);

			g2.scale(scaleX, scaleY);
			this.componentToBePrinted.paint(g2);
			response = 0;
		}
		enableDoubleBuffering(this.componentToBePrinted);
		return response;
	}

	public static void disableDoubleBuffering(Component c) {
		RepaintManager currentManager = RepaintManager.currentManager(c);
		currentManager.setDoubleBufferingEnabled(false);
	}

	public static void enableDoubleBuffering(Component c) {
		RepaintManager currentManager = RepaintManager.currentManager(c);
		currentManager.setDoubleBufferingEnabled(true);
	}public static void main(String[] args) {
		new PrintUtilities(new JLabel("35345"));
	}
	
}